package com.ddstation.onsitelaw.utils;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Date;

import static com.aliyun.oss.common.utils.IOUtils.safeClose;
import static com.aliyun.oss.common.utils.LogUtils.logException;
import static com.aliyun.oss.internal.OSSConstants.DEFAULT_BUFFER_SIZE;

public class AliCloudOssUtil {
	
	/**
	 * 获取原图  url
	 * @param bucketName
	 * @param key
	 * @return
	 */
    public static String getOriginImgUrl(String bucketName, String key) {

		OSSClient ossClient = new OSSClient(Constant.ossendpoint, Constant.accessKeyId, Constant.accessKeySecret);

    	if(StringUtils.isBlank(bucketName))
    		bucketName = Constant.bucketName;

        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + Constant.urlvaildtime);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);

        // 关闭client
        ossClient.shutdown();

        return url.toString();
    }
    
	/**
	 * 获取缩略图原图  url
	 * @param bucketName
	 * @param key
	 * @return
	 */
    public static String getThumbImgUrl(String bucketName, String key, String tmbStrategy) {

    	try {
			// 样式转换
			// @100h to  image/resize,m_fixed,h_100
			String style = null;
			if(StringUtils.isNotBlank(tmbStrategy)) {
				style = "image/resize,m_fixed,{0}_{1}";

				// 缩比方向（横or纵）
				String direction = tmbStrategy.substring(tmbStrategy.length() - 1, tmbStrategy.length());
				// h or w check
				if(!"w".equalsIgnoreCase(direction) && !"h".equalsIgnoreCase(direction))
					direction = "h";
				// 缩放数量
				String amount = tmbStrategy.substring(1, tmbStrategy.length() - 1);
				try {
					int _amount = Integer.parseInt(amount);
					if(_amount == 0) amount = "100";
				} catch(Exception e) {
					amount = "100";
				}
				style = MessageFormat.format(style, direction, amount);
			}

			return getSelfStyleImgUrl(bucketName, key, style);	// 会抛出异常
		} catch (Exception e) {
    		logger.error("getThumbImgUrl error -> ",e);
    		return "";
		}
    }
    
    /**
     * 自定义样式图片
     * @param bucketName
     * @param key
     * @param style
     * @return
     */
    public static String getSelfStyleImgUrl(String bucketName, String key, String style) {
    	OSSClient ossClient = new OSSClient(Constant.ossendpoint, Constant.accessKeyId, Constant.accessKeySecret);
    	
    	if(StringUtils.isBlank(bucketName))
    		bucketName = Constant.bucketName;
    	
    	// 图片处理样式
//    	String style = "image/resize,m_fixed,h_100";  
    	
        // 设置URL过期时间为1小时
    	Date expiration = new Date(new Date().getTime() + Constant.urlvaildtime);
        
    	// 生成URL
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
        req.setExpiration(expiration);
        if(StringUtils.isNotBlank(style))
        	req.setProcess(style);
        URL signedUrl = ossClient.generatePresignedUrl(req);
        // 关闭client
        ossClient.shutdown();
        
        return signedUrl.toString();
    }
    
    /**
     * 把http url的图片上传至阿里oss
     * @param bucketName
     * @param key
     * @param _url
     * @return
     */
    public static String putObject(String bucketName, String key, String _url) {
    	
    	if (StringUtils.isBlank(bucketName)) {
    		bucketName = Constant.bucketName;
    	}
    	
    	// 创建OSSClient实例
    	OSSClient ossClient = new OSSClient(Constant.ossendpoint, Constant.accessKeyId, Constant.accessKeySecret);
    	// 上传图片文件
    	InputStream inputStream = null;
        try {
            URL url = new URL(_url);  
            inputStream = new BufferedInputStream(url.openStream());
            ossClient.putObject(bucketName, key, inputStream);
            return key;
        } catch (IOException e) {
        	logger.error(e.getMessage());
        } catch (Exception e) {
        	logger.error(e.getMessage());
        } finally {
        	if (inputStream != null) {
        		try {
        			inputStream.close();
        		} catch(IOException e) {
        			logger.error(e.getMessage());
        		}
			}
        	// 关闭client
        	ossClient.shutdown();
		}
    	return null;
    }
    
    /**
     * 上传文件
     * @param bucketName
     * @param key
     * @return
     */
    public static String putOSSObject(String bucketName, String key, File file) {

		OSSClient ossClient = new OSSClient(Constant.ossendpoint, Constant.accessKeyId, Constant.accessKeySecret);
    	
    	if(StringUtils.isBlank(bucketName))
    		bucketName = Constant.bucketName;
    	
    	if(StringUtils.isBlank(key) || !file.exists() || !file.isFile())
    		throw new RuntimeException("阿里云oss 上传参数不对！！！");
    	
    	ossClient.putObject(bucketName, key, file);
    	
    	// 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + Constant.urlvaildtime);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
    	// 关闭client
    	ossClient.shutdown();
    	
    	return url.toString();
    }
    
    /**
     * 下载文件
     * @param bucketName
     * @param key
     * @return
     */
    public static void getOSSObject(String bucketName, String key, File file) {

		OSSClient ossClient = new OSSClient(Constant.ossendpoint, Constant.accessKeyId, Constant.accessKeySecret);
    	
    	if(StringUtils.isBlank(bucketName))
    		bucketName = Constant.bucketName;
    	
    	if(StringUtils.isBlank(key))
    		throw new RuntimeException("阿里云oss 上传参数不对！！！");
    	
    	ossClient.getObject(new GetObjectRequest(bucketName, key), file);
    
    	// 关闭client
    	ossClient.shutdown();
    	
    }
    
    /**
     * 删除文件
     * @param bucketName
     * @param key
     * @return
     */
    public static void delOSSObject(String bucketName, String key) {

		OSSClient ossClient = new OSSClient(Constant.ossendpoint, Constant.accessKeyId, Constant.accessKeySecret);
    	
    	if(StringUtils.isBlank(bucketName))
    		bucketName = Constant.bucketName;
    	
    	if(StringUtils.isBlank(key))
    		throw new RuntimeException("阿里云oss 上传参数不对！！！");
    	
    	ossClient.deleteObject(bucketName, key);
    
    	// 关闭client
    	ossClient.shutdown();
    	
    }
    
	/**
	 * 判断文件是否存在
	 * @param bucketName
	 * @param key
	 * @return
	 */
    public static boolean isExist(String bucketName, String key) {
		
		OSSClient ossClient = new OSSClient(Constant.ossendpoint, Constant.accessKeyId, Constant.accessKeySecret);
    	
    	if(StringUtils.isBlank(bucketName))
    		bucketName = Constant.bucketName;
    	
    	boolean found = ossClient.doesObjectExist(bucketName, key);
        
        // 关闭client
        ossClient.shutdown();
        
        return found;
    }
    
    
    public static JSONObject getImgInfo(String bucketName, String key, String style) {
		
		OSSClient ossClient = new OSSClient(Constant.ossendpoint, Constant.accessKeyId, Constant.accessKeySecret);
    	
    	if(StringUtils.isBlank(bucketName))
    		bucketName = Constant.bucketName;
    	
    	GetObjectRequest request = new GetObjectRequest(bucketName, key);
    	request.setProcess(style);
    	
    	OSSObject ossObject = ossClient.getObject(request);
    	StringBuilder info = new StringBuilder();
    	JSONObject imgInfoJson = null;
    	try {
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            
            while ((ossObject.getObjectContent().read(buffer)) != -1) {
            	info.append(new String(buffer));
            }
            
            if (info.length() > 0)
            	imgInfoJson = JSONObject.fromObject(info.toString());
            
        } catch (Exception ex) {
            logException("Cannot read object content stream: ", ex);
            logger.error(ex.getMessage());
        } finally {
            safeClose(ossObject.getObjectContent());
        }
    	
    	// 关闭client
        ossClient.shutdown();
        
        return imgInfoJson;
    }
    
    private static final Logger logger = LoggerFactory.getLogger(AliCloudOssUtil.class);
}
